﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.IntegrityCheck
{
    public class DataNotNullIC : IIntegrityCheck
    {
        public readonly static Guid ID = new Guid("{EB72A10E-37CC-41A2-ACA6-E5F3A3D7BED1}");

        public const string NAME = "数据非空验证插件";
        public const string DESCRIPTION = "检查数据指定的项是否为空数据，如果为空数据则视为有错误。";

        public bool Validate(DataServiceInterface.IData data, Dictionary<string, string> parameters, out string message)
        {
            bool hasError = false;
            StringBuilder errorMessageBuilder = new StringBuilder();

            string[] fields = null;
            try
            {
                fields = parameters["fields"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            catch(Exception ex)
            {
                message = ex.Message;
                return false;
            }

            for(int index = 0; index < data.RowCount; index++)
            {
                for(int fIndex = 0; fIndex < fields.Length; fIndex++)
                {
                    if(string.IsNullOrEmpty(data.Get(index).Get(fields[fIndex])))
                    {
                        errorMessageBuilder.AppendFormat("第{0}行的列{1}存在空数据不符合要求", index, fields[fIndex]);
                        hasError = true;
                    }
                }
            }
            if(hasError)
            {
                message = errorMessageBuilder.ToString();
                return false;
            }
            message = null;
            return true;
        }

        public List<Parameter> EnumParameters()
        {
            List<Parameter> parameters = new List<Parameter>();
            parameters.Add(new Parameter("fields", "字段(f1,f2,f3)", typeof(string)));
            return parameters;
        }

        public string GetConditionText(Dictionary<string, string> parameters)
        {
            StringBuilder builder = new StringBuilder();
            foreach (var key in parameters.Keys)
            {
                builder.AppendFormat("字段{0}不能为空值", parameters[key]);

            }
            return builder.ToString();
        }
    }
}